// posController(pos控制器)
const userModel = require('../model/userModel')
const jwt = require('jsonwebtoken')
const path = require('path')
const fs = require('fs')
// 定义注册方法
const signup = async (req, res) => {
  let username = req.body.username;
  let flag = await userModel.findOne({ username })
  if (flag) {//代表数据库已经存在这个用户了
    res.render('api.fail.ejs', {
      data: JSON.stringify({ message: '此用户名已经存在,请重新注册!' })

    })
  } else {
    let flag = await userModel.signup(req.body)
    flag
      ?
      res.render('api.succ.ejs', {
        data: JSON.stringify({ message: '恭喜你!注册成功!' })
      })
      :
      res.render('api.fail.ejs', {
        data: JSON.stringify({ message: '注册用户失败!' })
      })
  }
}

const signin = async function (req,res){
  let flag = await userModel.findOne(req.body)
  if(flag){
    let token = genToken({username:req.body.username})
    res.reader('api.succ.ejs',{
      data:JSON.stringify({message:'恭喜你!登陆成功!',token})
    })
  }else{
    res.render('api.fail.ejs',{
      data:JSON.stringify({message:'用户登陆失败!'})
    })
  }
}

// 生成token方法
// https://blog.csdn.net/qq_41875147/article/details/100315715
// 打开gitbush here运行
//生成私钥   openssl genrsa -out rsa_private_key.pem 2048
//生成公钥   openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
function genToken(data){
  const privateKey = fs.readFileSync(path.resolve(__dirname,'../keys/rsa_private_key.pem'))
  let token = jwt.sign(data,privateKey,{  algoritehm:'RS256',expiresIn:'60s' });
  return token
}

const issignin = async function(req,res){
  //需要从前端headers获取token字段
  const token = req.headers.tokenconst 
  const cert = fs.readFileSync(path.resolve(__dirname,'../keys/rsa_public_key.pem'))
  //需要对私钥加密的token令牌进行公钥解密  (非对称加密算法)
  jwt.verify(token,cert, function(err, decoded) {
    if(!err){
      res.render('api.succ.ejs',{
        data:JSON.stringify({username:decoded.username})
      })
    }else{
      res.render('api.fail.ejs',{
        data:'用户验证失败!'
      })
    }
  })
}
module.exports = {
  signup,signin,issignin
}